import os
import json
import requests

# 定义 API 地址
UPLOAD_LEVEL_URL = "http://106.54.192.233:8080/uploadLevel"  # 替换为实际后台地址

# 批量上传 JSON 文件的函数
def batch_upload_levels(json_folder_path, author="lulu", overwrite=False):
    # 遍历指定文件夹下的所有 JSON 文件
    for root, _, files in os.walk(json_folder_path):
        for file in files:
            if file.endswith(".json"):
                file_path = os.path.join(root, file)
                try:
                    # 读取 JSON 文件
                    with open(file_path, "r", encoding="utf-8") as f:
                        level_data = json.load(f)

                    # 构建上传的 payload
                    payload = {
                        "title": level_data.get("title"),
                        "author": author,
                        "query": level_data.get("desprition"),
                        "description": level_data.get("desprition"),
                        "code": level_data.get("code"),
                        "data": level_data.get("code"),
                        "overwrite": overwrite
                    }

                    # 发送 POST 请求
                    response = requests.post(UPLOAD_LEVEL_URL, json=payload)

                    # 处理响应
                    if response.status_code == 200:
                        print(f"文件 {file} 上传成功: {response.json()}")
                    else:
                        print(f"文件 {file} 上传失败，状态码: {response.status_code}, 响应: {response.text}")

                    # return

                except Exception as e:
                    print(f"文件 {file} 上传时发生错误: {e}")

# 指定 JSON 文件夹路径
json_folder = "lulu_exp/new_levels"

# 调用批量上传函数
batch_upload_levels(json_folder_path=json_folder)
